//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Media;
using OpenLS.Chart.UI.Internals;

namespace OpenLS.Chart.UI
{
    class LineSeriesToGeometryConverter : IMultiValueConverter
    {
        #region IMultiValueConverter Members

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var series = (LineSeries)values[0];
            var chart = StrictConverter.Convert<ChartBase>(values[1]);
            if (chart == null)
            {
                Debug.WriteLine("Return null");
                return null;
            }
            var width = (double)values[2];
            var height = (double)values[3];
            var min = (double)values[4];
            var max = (double)values[5];
          
            AxisOrientation orientation = StrictConverter.Convert(values[6], AxisOrientation.MinimumToMaximum);
            AxisOrientation categoryOrientation = StrictConverter.Convert(values[7], AxisOrientation.MinimumToMaximum);
            var isSmooth = (bool) values[8];
            if (values[9] == DependencyProperty.UnsetValue)
            {
                Debug.WriteLine("return null (2)");
                return null;
            }
            var maxValueCount = (int)values[9];

            var points = new PointCollection();
            var numericValues = new List<NumericValue>(series.Values.NumericValues);
            ChartLayout info = ChartToChartInfoConverter.GetInfo(chart);
            var projector = new ValueAxisProjector(min, max, height, 0, orientation);
            try
            {
                foreach (NumericValue numericValue in numericValues)
                {
                    double x = CategoryAxisPanel.GetScreenPosition(numericValue.Index, 0, maxValueCount, 0, width,
                                                                   categoryOrientation, true); //\\for now
                    double y = projector.GetValue(info.GetValue(numericValue, series, 0));
                    points.Add(new Point(x, y));
                }
            }
            catch
            {
                // Contract.Assert(false);
                return null;
            }
            var result =  CurveFactory.CreateCurve(points, isSmooth);
            Debug.WriteLine(XamlWriter.Save(result));
            return result;
        }


        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        #endregion
    }
}
